package com.cyl.yeepay.setvice;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cyl.manager.yee.domain.YeeMerchant;
import com.cyl.pay.dto.xw.WxRwDto;
import com.cyl.yeepay.config.YeePayConfig;
import com.ruoyi.system.service.ISysConfigService;
import com.sun.xml.bind.v2.schemagen.xmlschema.List;
import com.yeepay.yop.sdk.exception.YopClientException;
import com.yeepay.yop.sdk.service.account.AccountClient;
import com.yeepay.yop.sdk.service.account.AccountClientBuilder;
import com.yeepay.yop.sdk.service.account.model.WithdrawCardBindBindCardRespDTOResult;
import com.yeepay.yop.sdk.service.account.model.WithdrawCardModifyModifyBindCardRespDTOResult;
import com.yeepay.yop.sdk.service.account.request.WithdrawCardBindRequest;
import com.yeepay.yop.sdk.service.account.request.WithdrawCardModifyRequest;
import com.yeepay.yop.sdk.service.account.response.WithdrawCardBindResponse;
import com.yeepay.yop.sdk.service.account.response.WithdrawCardModifyResponse;
import com.yeepay.yop.sdk.service.mer.MerClient;
import com.yeepay.yop.sdk.service.mer.MerClientBuilder;
import com.yeepay.yop.sdk.service.mer.model.RegisterQueryV2NetInProgressQueryRespDtoResult;
import com.yeepay.yop.sdk.service.mer.model.RegisterSaasIndexV2UserPreRegisterRespDtoResult;
import com.yeepay.yop.sdk.service.mer.model.RegisterSaasMicroV2ContributeMicroMerchantNetInRespDtoResult;
import com.yeepay.yop.sdk.service.mer.model.RegisterSaasWebIndexV2CreateNetInUrlRespDTOResult;
import com.yeepay.yop.sdk.service.mer.request.RegisterQueryV2Request;
import com.yeepay.yop.sdk.service.mer.request.RegisterSaasIndexV2Request;
import com.yeepay.yop.sdk.service.mer.request.RegisterSaasMicroV2Request;
import com.yeepay.yop.sdk.service.mer.request.RegisterSaasWebIndexV2Request;
import com.yeepay.yop.sdk.service.mer.response.RegisterQueryV2Response;
import com.yeepay.yop.sdk.service.mer.response.RegisterSaasIndexV2Response;
import com.yeepay.yop.sdk.service.mer.response.RegisterSaasMicroV2Response;
import com.yeepay.yop.sdk.service.mer.response.RegisterSaasWebIndexV2Response;
import com.yeepay.yop.sdk.service.sys.SysClient;
import com.yeepay.yop.sdk.service.sys.SysClientBuilder;
import com.yeepay.yop.sdk.service.sys.model.MerchantQualUploadMerFileUploadRespDtoResult;
import com.yeepay.yop.sdk.service.sys.request.MerchantQualUploadRequest;
import com.yeepay.yop.sdk.service.sys.response.MerchantQualUploadResponse;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class YeePayMerService {

 
    // 该Client线程安全，请使用单例模式，多次请求共用
    private static final MerClient merClient = MerClientBuilder.builder().build();
    @Autowired
    private YeePayConfig yeePayConfig;
    @Autowired
    private ISysConfigService configService;
    private static final AccountClient accountClient = AccountClientBuilder.builder().build();

 // 该Client线程安全，请使用单例模式，多次请求共用
    private static final SysClient sysClient = SysClientBuilder.builder().build();

    

    public RegisterSaasMicroV2ContributeMicroMerchantNetInRespDtoResult registerSaasMicroV2(WxRwDto rw) {
    	RegisterSaasMicroV2Request request = new RegisterSaasMicroV2Request();
        request.setRequestNo(rw.getRequestNo());
        request.setBusinessRole("SETTLED_MERCHANT");
        
        
        ArrayList<Map<String, Object>> productInfo = new ArrayList<Map<String, Object>>();
        
        HashMap<String, Object> productInfo1 = new HashMap<String, Object>();
        productInfo1.put("productCode", "ENTERPRISE_WITHDRAW_STANDARD_REALTIME");
        productInfo1.put("rateType", "SINGLE_FIXED");
        productInfo1.put("fixedRate","0");
        productInfo1.put("paymentMethod", "REAL_TIME");
        
        
        HashMap<String, Object> productInfo2 = new HashMap<String, Object>();
        productInfo2.put("productCode", "D1_MANUAL");
        productInfo2.put("rateType", "SINGLE_FIXED");
        productInfo2.put("fixedRate", "0");
        productInfo1.put("paymentMethod", "REAL_TIME");

        productInfo.add(productInfo1);
        productInfo.add(productInfo2);

        request.setProductInfo(JSONUtil.toJsonStr(productInfo));
        
        
 	   request.setParentMerchantNo(yeePayConfig.getParentMerchantNo());
        request.setMerchantSubjectInfo(JSONUtil.toJsonStr(rw.getMerchantSubjectInfo()));
        request.setMerchantCorporationInfo(JSONUtil.toJsonStr(rw.getMerchantCorporationInfo()));
        request.setBusinessAddressInfo(JSONUtil.toJsonStr(rw.getBusinessAddressInfo()));
        request.setAccountInfo(JSONUtil.toJsonStr(rw.getAccountInfo()));
        request.setNotifyUrl(yeePayConfig.getNotifyOutUrl().replaceAll("out", "regxw"));//注册成功后，易宝将商户请求流水号及对应的商户编号返回到此地址
    	
        RegisterSaasMicroV2ContributeMicroMerchantNetInRespDtoResult result = null;
    	
    	try {
            RegisterSaasMicroV2Response  response =   merClient.registerSaasMicroV2(request);
            result = response.getResult();
            if( !"NIG00000".equals(result.getReturnCode())) {
             	throw new RuntimeException("操作失败！code:"+result.getReturnCode() + " msg:"+result.getReturnMsg());
            }
            log.info("result:{}", response.getResult());
        } catch (YopClientException e) {
        	log.error("Exception when calling MerClient#registerContributeMicroV2, ex:", e);
           	throw new RuntimeException("操作失败！YopClientException:merClient#registerSaasMicroV2"+e.getMessage());

        }
		return result;
    }

    
    
    
    
    public MerchantQualUploadMerFileUploadRespDtoResult merchantQualUpload(File file) {
    	MerchantQualUploadMerFileUploadRespDtoResult result = null;
        MerchantQualUploadRequest request = new MerchantQualUploadRequest();
        request.setMerQual(file);
        try {
            MerchantQualUploadResponse response = sysClient.merchantQualUpload(request);
            log.info("result:{}", response.getResult());
            result = response.getResult();
            if( !"REG00000".equals(result.getReturnCode())) {
             	throw new RuntimeException("操作失败！code:"+result.getReturnCode() + " msg:"+result.getReturnMsg());
            }
        } catch (YopClientException e) {
        	log.error("Exception when calling SysClient#merchantQualUpload, ex:", e);
           	throw new RuntimeException("操作失败！YopClientException:SysClient#merchantQualUpload"+e.getMessage());

        }
		return result;
    }
    
    
    public  RegisterSaasIndexV2UserPreRegisterRespDtoResult registerSaasIndexV2(String requestNo,String mobile,String name,String idCardNo) {
    	RegisterSaasIndexV2UserPreRegisterRespDtoResult result = null;
    	   RegisterSaasIndexV2Request request = new RegisterSaasIndexV2Request();
    	   request.setParentMerchantNo(yeePayConfig.getParentMerchantNo());
           request.setRequestNo(requestNo);//请求流水号需保证唯一，与‘入网h5页面地址’唯一对应， 如， 未完成注册，返回链接跳转至‘注册用户’页面； 已完成注册，返回链接跳转至‘注册信息’页面；
           request.setNotifyUrl(yeePayConfig.getNotifyOutUrl().replaceAll("out", "regxw"));//注册成功后，易宝将商户请求流水号及对应的商户编号返回到此地址
           request.setReturnUrl(yeePayConfig.getRefundRegisterXwUrl());//注册用户后返回商户的页面地址
           request.setMobile(mobile);//用户在平台的注册手机号 
           request.setName(name);//用户在平台认证过的姓名，需要与身份证号同时上送，用于展示在‘注册用户’页面 ‘姓名、身份证号’与‘钱包账户ID’不允许同时上送
           request.setIdCardNo(idCardNo);//用户在平台认证过的身份证号，需要与姓名同时上送，用于展示在‘注册用户’页面
//           request.setWalletUserNo("示例值：User89849");//注册钱包时，易宝返回的账户ID（易宝钱包唯一编号），用于获取‘姓名、身份证号’展示在‘注册用户’页面 ‘姓名、身份证号’与‘钱包账户ID’不允许同时上送 
           try {
        	   RegisterSaasIndexV2Response response = merClient.registerSaasIndexV2(request);
               log.info("result:{}", response.getResult());
               result = response.getResult();
               if( !"MAS000000".equals(result.getCode())) {
                	throw new RuntimeException("操作失败！code:"+result.getCode() + " msg:"+result.getMsg() );
               }
           } catch (YopClientException e) {
             	 log.error("Exception when calling merClient#registerSaasIndexV2, ex:", e);
               	throw new RuntimeException("操作失败！YopClientException:registerSaasIndexV2"+e.getMessage());
            }
		return result;
    }
    
    

    public RegisterQueryV2NetInProgressQueryRespDtoResult registerQueryV2(String requestNo) {
    	 RegisterQueryV2Request request = new RegisterQueryV2Request();
    	 RegisterQueryV2NetInProgressQueryRespDtoResult dtoResult = null;
         request.setRequestNo(requestNo);
         try {
             RegisterQueryV2Response response = merClient.registerQueryV2(request);
             log.info("result:{}", response.getResult());
             dtoResult = response.getResult();
         } catch (YopClientException e) {
        	 log.error("Exception when calling MerClient#registerQueryV2, ex:", e);
             throw new RuntimeException("查询失败！YopClientException:registerSaasIndexV2"+e.getMessage());
         }
		return dtoResult;
    }
    

    public  RegisterSaasWebIndexV2CreateNetInUrlRespDTOResult registerSaasWebIndexV2() {
    	RegisterSaasWebIndexV2CreateNetInUrlRespDTOResult result = null;
    	RegisterSaasWebIndexV2Request request = new RegisterSaasWebIndexV2Request();
        request.setRequestNo("fba1dd39fd3846b4901f5a833fa3baa3");
        request.setSignType("ENTERPRISE");
        request.setNotifyUrl("http://www.yeepay.com/merchant/notify");
        request.setReturnUrl("http://www.yeepay.com");
        request.setProductTemplateNo("CP166748***3516");
        request.setMerchantBaseInfo("{ \"signName\":\"商户签约名\", \"licenceNo\":\"商户证件号码\"}");
        request.setCorporationInfo("{ \"legalName\":\"法人名称\",  \"legalLicenceNo\":\"法人证件编号\"}");
        request.setContactInfo("{ \"contactName\":\"联系人姓名\", \"contactMobile\":\"联系人手机号\", \"contactEmail\":\"联系人邮箱\", \"contactLicenceNo\":\"联系人证件号码\" ,\"servicePhone\":\"客服电话\"}");
        request.setBusinessAddressInfo("{ \"address\":\"商户实际经营地址\"}");
        try {
        	RegisterSaasWebIndexV2Response response = merClient.registerSaasWebIndexV2(request);
            log.info("result:{}", response.getResult());
            result = response.getResult();
        } catch (YopClientException e) {
        	log.error("Exception when calling MerClient#registerContributeWebIndexV2, ex:", e);
        }
		return result;
    }
    

    

    /**
     *  修改提现卡
     * @param merchantNo
     * @return
     */
      public boolean updateBankCard(YeeMerchant yeeMerchant) {
    	  WithdrawCardModifyRequest request = new WithdrawCardModifyRequest();
          request.setMerchantNo(yeeMerchant.getMerchantNo());
          request.setAccountNo(yeeMerchant.getAccountNo());
          request.setBindId(Long.parseLong(yeeMerchant.getBindId()));
          request.setBankCode(yeeMerchant.getBankCode());
          request.setBranchCode(yeeMerchant.getBranchCode());
          request.setBankCardOperateType("MODIFY");
          boolean success = false;
          try {
              WithdrawCardModifyResponse response = accountClient.withdrawCardModify(request);
              WithdrawCardModifyModifyBindCardRespDTOResult dTOResult =  response.getResult();
              log.info("result:{}", dTOResult);
              if("UA00000".equals(dTOResult.getReturnCode())) {
            	  success = true;
              }else {
                  throw new RuntimeException("修改提现卡失败，code:"+dTOResult.getReturnCode()+" msg: "+dTOResult.getReturnMsg());
              }
          } catch (YopClientException e) {
        	  log.error("Exception when calling AccountClient#withdrawCardModify, ex:", e);
          	throw new RuntimeException("修改提现卡失败！YopClientException:"+e.getMessage());
          }
           
   		return success;
      }
    
    
    /**
     *  添加提现卡
     * @param merchantNo
     * @return
     */
      public Long addBankCard(YeeMerchant yeeMerchant) {
    	  WithdrawCardBindBindCardRespDTOResult dTOResult = null;
    	  WithdrawCardBindRequest request = new WithdrawCardBindRequest();
          request.setMerchantNo(yeeMerchant.getMerchantNo());
          request.setBankCardType(yeeMerchant.getBankCardType());
          request.setAccountNo(yeeMerchant.getAccountNo());
          request.setBankCode(yeeMerchant.getBankCode());
          request.setBranchCode(yeeMerchant.getBranchCode());
          Long bindId = null;
          try {
              WithdrawCardBindResponse response = accountClient.withdrawCardBind(request);
              dTOResult =  response.getResult();
              log.info("result:{}", dTOResult);
              if("UA00000".equals(dTOResult.getReturnCode())) {
            	  bindId = dTOResult.getBindId();
              }else {
                  throw new RuntimeException("添加提现卡失败，code:"+dTOResult.getReturnCode()+" msg: "+dTOResult.getReturnMsg());
              }
          } catch (YopClientException e) {
        	  log.error("YopClientException Exception when calling AccountClient#withdrawCardBind, ex:", e);
            	throw new RuntimeException("添加提现卡失败！YopClientException:"+e.getMessage());
          }
           
   		return bindId;
      }
    
}
